//
//  ZXY_ScrollPageInfinite.m
//  ZXY_ScrollInfiniteOC
//
//  Created by 宇周 on 15/12/10.
//  Copyright © 2015年 宇周. All rights reserved.
//

#import "ZXY_ScrollPageInfinite.h"
#import "ZXY_ScrollCollectionCell.h"
#import <AFNetworking/AFNetworking.h>
#import <UIKit+AFNetworking.h>

@interface ZXY_ScrollItemData : NSObject

@property(nonatomic , strong)NSString *imgURL;
@property(nonatomic , strong)NSNumber *currentIndex;
-(id)deepCopy;

@end

@implementation ZXY_ScrollItemData

- (id)deepCopy
{
    ZXY_ScrollItemData *nData = [[ZXY_ScrollItemData alloc] init];
    nData.imgURL = [NSString stringWithFormat:@"%@",self.imgURL];
    nData.currentIndex = [NSNumber numberWithInt:self.currentIndex.intValue];
    return nData;
}
@end

@interface ZXY_ScrollPageInfinite()<UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout>
{
    BOOL isDrag;
    BOOL isLocalImgs;
    NSInteger currentDownIndex;
    BOOL isAllDown;
}
@property(nonatomic , strong)UICollectionView *currentCollectView;
@property(nonatomic , strong)UICollectionViewFlowLayout *layout;
@property(nonatomic , strong)NSMutableArray *scrollDatas ;
@property(nonatomic , strong)NSTimer *scrollTimer;
@property(nonatomic , strong)NSArray *imgUrlS ;
@property(nonatomic , strong)NSArray *imgs;
@property(nonatomic , strong)NSMutableArray *allDownURL;
@property(nonatomic , strong)UIImageView *tempImg;
@end

@implementation ZXY_ScrollPageInfinite
CGSize sizeOfScreen;
- (id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self initCollectWithFrame];
        [self initData];
    }
    return self;
}

- (void)awakeFromNib
{
    [self initData];
    [self initCollectWithFrame];
}

- (void)initData
{
    isDrag = NO;
    isAllDown = NO;
    isLocalImgs = NO;
    self.timeInterval = 2;
    currentDownIndex = 0;
    sizeOfScreen = [UIScreen mainScreen].bounds.size;
    self.scrollDatas = [[NSMutableArray alloc] init];
}

- (void)initCollectWithFrame
{
    if(self.currentCollectView == nil)
    {
        [self setLayoutOfCollect];
        self.currentCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, sizeOfScreen.width, self.frame.size.height) collectionViewLayout:self.layout];
        self.currentCollectView.contentOffset = CGPointZero;
        self.currentCollectView.pagingEnabled = YES;
        [self.currentCollectView registerClass:[ZXY_ScrollCollectionCell class] forCellWithReuseIdentifier:@"cellID"];
        self.currentCollectView.delegate = self;
        self.currentCollectView.dataSource = self;
        self.currentCollectView.showsHorizontalScrollIndicator = NO;
        self.currentCollectView.showsVerticalScrollIndicator   = NO;
        self.currentCollectView.backgroundColor = [UIColor clearColor];
        [self.currentCollectView reloadData];
        [self addSubview:self.currentCollectView];
    }
}


/**
 *  设置layout
 */
- (void)setLayoutOfCollect
{
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.layout.minimumLineSpacing = 0;
    self.layout.minimumInteritemSpacing = 0;
    self.layout.sectionInset = UIEdgeInsetsZero;
}

- (void)setIMGURL:(NSArray *)imgURLS
{
    self.imgUrlS = [[NSMutableArray alloc] initWithArray:imgURLS];
    [self downImg];
    [self configureData];
}

- (void)setIMGS:(NSArray *)imgs
{
    isLocalImgs = YES;
    self.imgs = [[NSMutableArray alloc] initWithArray:imgs];
    [self configureData];
}

- (void)downImg
{
    __weak ZXY_ScrollPageInfinite *weakSelf = self;
    if(self.allDownURL == nil)
    {
        self.allDownURL = [[NSMutableArray alloc] init];
    }
    
    if(self.tempImg == nil)
    {
        self.tempImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)];
    }
    
    if(currentDownIndex < self.imgUrlS.count)
    {
        NSURL *imgURL = [NSURL URLWithString:[self.imgUrlS[currentDownIndex] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
        [self.tempImg setImageWithURLRequest:[NSURLRequest requestWithURL:imgURL] placeholderImage:self.placeHolderImg success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
            currentDownIndex ++;
            [weakSelf downImg];
            [weakSelf.allDownURL addObject:imgURL];
   } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            currentDownIndex ++;
            [weakSelf downImg];
        }];
    }
    else
    {
        isAllDown = YES;
    }
    
}

/**
 *  构造数据
 */
- (void)configureData
{
    if(isLocalImgs)
    {
        if(self.imgs.count > 0)
        {
            for(int i = 0 ; i < self.imgs.count ; i++)
            {
                ZXY_ScrollItemData *data = [[ZXY_ScrollItemData alloc] init];
                NSString *currentImgs = [self.imgs objectAtIndex:i];
                NSNumber *currentIndex = [NSNumber numberWithInt:i];
                data.currentIndex = currentIndex;
                data.imgURL = currentImgs;
                [self.scrollDatas addObject:data];
            }

        }
        else if (self.imgs.count <= 1)
        {
            self.currentCollectView.scrollEnabled = NO;
        }
        [self.currentCollectView reloadData];
        return;
    }
    if(self.imgUrlS.count > 0)
    {
        for(int i = 0 ; i < self.imgUrlS.count ; i++)
        {
            ZXY_ScrollItemData *data = [[ZXY_ScrollItemData alloc] init];
            NSString *currentImgs = [self.imgUrlS objectAtIndex:i];
            NSNumber *currentIndex = [NSNumber numberWithInt:i];
            data.currentIndex = currentIndex;
            data.imgURL = currentImgs;
            [self.scrollDatas addObject:data];
        }
        if(self.imgUrlS.count <= 1)
        {
            self.currentCollectView.scrollEnabled = NO;
        }
        [self.currentCollectView reloadData];
    }
    return;
}



/**
 *  起timer
 */
- (void)startTimer
{
    if(self.scrollDatas.count <= 1)
    {
        return;
    }
    if(self.scrollTimer == nil)
    {
        self.scrollTimer = [NSTimer timerWithTimeInterval:self.timeInterval target:self selector:@selector(scrollWithTimer) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.scrollTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)scrollWithTimer
{
    [self.currentCollectView setContentOffset:CGPointMake(self.currentCollectView.contentOffset.x + sizeOfScreen.width, 0) animated:YES];
}


#pragma mark

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.scrollDatas.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZXY_ScrollItemData *currentData = [self.scrollDatas objectAtIndex:indexPath.row];
    ZXY_ScrollCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
    if(!isLocalImgs)
    {
        NSURL *imgURL = [NSURL URLWithString:[currentData.imgURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
        if(isAllDown)
        {
        
            [cell.img setImageWithURL:imgURL placeholderImage:self.placeHolderImg];
        }
        else
        {
            if([self.allDownURL containsObject:imgURL])
            {
                [cell.img setImageWithURL:imgURL placeholderImage:self.placeHolderImg];
            }
            else
            {
                cell.img.image = self.placeHolderImg;
            }
        }
    }
    else
    {
        cell.img.image = [UIImage imageNamed:currentData.imgURL];
    }
    if(self.delegate && !isDrag)
    {
        [self.delegate pageChangeCurrentPageAtIndex:[currentData.currentIndex integerValue]];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZXY_ScrollItemData *currentData = [self.scrollDatas objectAtIndex:indexPath.row];
    if(self.delegate)
    {
        [self.delegate userClickPageScrollAtIndex:[currentData.currentIndex integerValue]];
    }
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(sizeOfScreen.width, collectionView.frame.size.height);
}

//对数据进行控制
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger currentOffset = scrollView.contentOffset.x;
    if(currentOffset < 0)
    {
        ZXY_ScrollItemData *dataLast = [(ZXY_ScrollItemData *)[self.scrollDatas objectAtIndex:self.scrollDatas.count - 1]  deepCopy];
        [self.scrollDatas insertObject:dataLast atIndex:0];
        [self.scrollDatas removeObjectAtIndex:self.scrollDatas.count - 1];
        [self.currentCollectView setContentOffset:CGPointMake(sizeOfScreen.width, 0)];
    }
    
    if(currentOffset > sizeOfScreen.width * (self.scrollDatas.count -1))
    {
        ZXY_ScrollItemData *dataFirst = [(ZXY_ScrollItemData *)[self.scrollDatas objectAtIndex:0]  deepCopy];
        [self.scrollDatas addObject:dataFirst];
        [self.scrollDatas removeObjectAtIndex:0];
        [self.currentCollectView setContentOffset:CGPointMake(sizeOfScreen.width * (self.scrollDatas.count - 2), 0)];
    }
    [self.currentCollectView reloadData];
    
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    //校验整数
    CGFloat off = self.currentCollectView.contentOffset.x;
    CGFloat sizeUnit = sizeOfScreen.width;
    NSInteger multi = roundf( off / sizeUnit );
    CGFloat sizeOff = multi * sizeOfScreen.width;
    [self.currentCollectView setContentOffset:CGPointMake(sizeOff, 0) ];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    isDrag = YES;
    
    [self.scrollTimer invalidate];
    self.scrollTimer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    isDrag = NO;
    [self startTimer];
}

#pragma mark 
@end
